import axios, {AxiosRequestConfig} from "axios";
import {rejects} from "assert";

//请求时间超出设置时间后，如果没有请求成功就执行错误函数。
axios.defaults.timeout = 200 * 1000;
//客户端做了一些上传的限制
axios.defaults.maxBodyLength = 5 * 1024 * 1024;
//前端跨域传递Cookie设置
axios.defaults.withCredentials = true;
axios.defaults.baseURL = 'http://localhost:5000';

axios.interceptors.request.use(
    (config: AxiosRequestConfig | any) => {
        config.params = {
            ...config.params,
            t: Date.now(),
        };
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        return Promise.reject(error);
    }
);

interface ResType<T> {
    code: number;
    data?: T;
    msg: string;
    err?: string;
}

interface Http {
    get<T>(url: string, params?: unknown): Promise<T>;

    post<T>(url: string, params?: unknown): Promise<T>;

    upload<T>(url: string, params: unknown): Promise<T>;

    put<T>(url: string, params: unknown): Promise<T>;

    delete<T>(url: string, params: unknown): Promise<T>;

    download(url: string): void;
}

const http: Http = {
    get(url, params) {
        return new Promise((resolve, reject) => {
            axios.get(url, {params}).then((res) => {
                resolve(res.data);
            }).catch((err) => {
                reject(err.data);
            })
        })
    },
    post(url, params) {
        return new Promise((resolve, reject) => {
            axios.post(url, JSON.stringify(params)).then((res) => {
                resolve(res.data);
            }).catch((err) => {
                reject(err.data);
            })
        })
    },
    put(url, params) {
        return new Promise((resolve, reject) => {
            axios.put(url, JSON.stringify(params)).then((res) => {
                resolve(res.data);
            }).catch((err) => {
                reject(err.data);
            })
        })
    },
    delete(url, params) {
        return new Promise((resolve, reject) => {
            axios.delete(url, {params}).then((res) => {
                resolve(res.data);
            }).catch((err) => {
                    reject(err.data);
            });
        });
    },
    upload(url, file) {
        return new Promise((resolve, reject) => {
            axios.post(url, file, {
                headers: {"Content-Type": "multipart/form-data"},
            }).then((res) => {
                resolve(res.data);
            }).catch((err) => {
                reject(err.data);
            });
        });
    },
    download(url) {
        const iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.src = url;
        iframe.onload = function () {
            document.body.removeChild(iframe);
        };
        document.body.appendChild(iframe);
    }
};

export default http;
